$(document).ready(function() {
    // Initialize addNoteView
    SB.addNoteView = new SB.AddNoteView();
    console.log(SB.addNoteView.render().el);

    // Setup popover setting
    $("a[rel=popover]").popover({
        trigger : 'manual',
        placement : function(tip, element) {
            var offset = $(element).offset();
            width = $(document).outerWidth();
            horiz = 0.5 * width - offset.left;
            placement = horiz > 0 ? 'right' : 'left';
            return placement;
        },
        html : true,
        content : SB.addNoteView.el
    }).click(function(e) {
        e.preventDefault();
    });

    // This is to patch for SB.addNoteView inside Bootstrap popover
    $(document).on('click', '#create-note', function() {
        SB.addNoteView.createNote();
    });

    // Backbone startup
    SB.articleCollectionView = new SB.ArticleCollectionView({
        el : ".articles"
    });
    SB.articleCollectionView.render();

    // Setup ScrollMore
    ScrollMore.opts.nextUrl = $('a#next').attr('href');
    var before = function() {
        SB.showLoading();
    };
    var success = function(data) {
        SB.hideLoading();
        data = JSON.parse(data);
        // Append to current content
        $('.articles').append(data.html);
        var json = data.json;
        for (var i=0; i<json.length; i++) {
            var obj = json[i];
            var articleModel = new SB.ArticleModel();
            articleModel.set(obj);
            SB.articleCollection.push(articleModel);
        }
        
        if (data.cursor) {
            ScrollMore.opts.nextUrl = "/api/article/cursor/?curs=" + encodeURIComponent(data.cursor);
        } else {
            ScrollMore.opts.nextUrl = "";
        }
    };
    var error = function() {
        SB.hideLoading();
    };
    ScrollMore.init(before, success, error);
});
